var encryptUtils = require('../utils/encrypt-utils'),
	UserInfo = require('../models/user-info'),
	securityBiz = require('../../frame/biz/security-biz'),
	_ = require('underscore'),
	UserBiz = {
		create: function(username, password, callback) {
			var param = {
				username: username,
				password: encryptUtils.encryptByMD5(password),
				createTime: new Date(),
				prvKey: encryptUtils.encryptByMD5(username + password + Math.round(Math.random()*1000000))
			}

			UserInfo.create(param, callback);
		},
		findUserByParam: function(param, callback) {
			var userParam = {
				username: param.username,
				password: encryptUtils.encryptByMD5(param.password)
			}, opt = {
				username: 1,
				prvKey: 1,
				_id: 0
			};

			this.validLogin(param,function(flag){
				if(flag){
					UserInfo.find(userParam,opt, function(err, doc) {
						var record;
						err = err ? err : 10001;
						callback(err,doc);
						if(_.isArray(doc) && doc.length === 0 ){
							record = {
								ip: param.ip,
								funcid: "/frame/biz/user-biz/findUserByParam",
								input: JSON.stringify(param)
							};
							securityBiz.saveLoginFail(record,function(){});
						}

					});
				}else{
					callback(-100001,"您因为多次异常操作被限制访问本系统。");
				}
			});


		},
		validLogin: function (param,callback) {
			var secuParam = {};
			secuParam.ip = param.ip;
			secuParam.funcid = "/frame/biz/user-biz/findUserByParam";
			securityBiz.findRecord(secuParam,function(doc){
				if(doc.length === 0 || (doc.length>0 && doc[0].count < 5)){
					callback(true);
				}else{
					callback(false);
				}

			});
		},
		updatePwd: function(param){
			var userParam = {
				password: encryptUtils.encryptByMD5(param.password)
			},conditions = {
				username: param.username
			};
			return new Promise(function (resolve,reject) {
				UserInfo.update(conditions,userParam,{upsert : true},function (err,doc) {
					resolve(doc);
				});
			});
		}
	};

module.exports = UserBiz;